package com.zenithmind.gateway.route;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 内容管理相关服务路由配置器
 * 专门负责文章、笔记、新闻、文档、商城服务的路由配置
 * 遵循单一职责原则：只负责内容管理相关的路由配置
 */
@Slf4j
@Component
public class ContentManagementRouteConfigurer implements RouteConfigurer {

    @Override
    public void configureRoutes(Builder routes) {
        log.info("配置内容管理相关服务路由...");
        
        // 文章服务路由 - 文章、分类、标签
        routes.route("article-service-route", r -> r
            .path("/api/zenithMind/article/**", 
                 "/api/zenithMind/article-category/**", 
                 "/api/zenithMind/tag/**",
                 "/api/zenithMind/category/**")
            .uri("lb://article-service"));
        
        // 笔记服务路由 - 笔记、笔记本、标签
        routes.route("note-service-route", r -> r
            .path("/api/zenithMind/note/**",
                 "/api/zenithMind/notebook/**",
                 "/api/zenithMind/note-tag/**")
            .uri("lb://note-service"));
            
        // 新闻服务路由 - 新闻、公告、资讯
        routes.route("news-service-route", r -> r
            .path("/api/zenithMind/news/**",
                 "/api/zenithMind/announcement/**",
                 "/api/zenithMind/api/v1/news/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/news"))
            .uri("lb://news-service"));
            
        // 文档服务路由 - 文档、模板、协作
        routes.route("document-service-route", r -> r
            .path("/api/zenithMind/document/**",
                 "/api/zenithMind/template/**",
                 "/api/zenithMind/doc/**",
                 "/api/zenithMind/api/v1/documents/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/documents"))
            .uri("lb://document-service"));
            
        // 商城服务路由 - 商品、订单、支付
        routes.route("mall-service-route", r -> r
            .path("/api/zenithMind/mall/**",
                 "/api/zenithMind/product/**",
                 "/api/zenithMind/order/**",
                 "/api/zenithMind/payment/**",
                 "/api/zenithMind/api/v1/mall/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/mall"))
            .uri("lb://mall-service"));
    }

    @Override
    public String getConfigureName() {
        return "ContentManagementRouteConfigurer";
    }

    @Override
    public int getOrder() {
        return 2;
    }
    
    /**
     * 路径过滤器工具方法 - 专用于/api/zenithMind/api/v1/前缀的路径
     * 如果路径以指定前缀开头，则移除前缀
     */
    private GatewayFilterSpec pathFilterForApiV1(GatewayFilterSpec f, String prefixPattern) {
        return f.rewritePath("/api/zenithMind/api/v1/(?<segment>.*)", "/api/zenithMind/${segment}");
    }
}
